'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';


interface SystemConfig {
  id: string;
  key: string;
  name: string;
  value: string;
  type: 'text' | 'number' | 'boolean' | 'json';
  category: string;
  description: string;
  updatedAt: string;
}

export default function ConfigsPage() {
  const { user } = useAuth();
  const router = useRouter();
  const [configs, setConfigs] = useState<SystemConfig[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [editingConfig, setEditingConfig] = useState<SystemConfig | null>(null);
  const [selectedCategory, setSelectedCategory] = useState<string>('all');

  // 模拟配置数据
  const mockConfigs: SystemConfig[] = [
    {
      id: '1',
      key: 'site_name',
      name: '网站名称',
      value: '汽车展示系统',
      type: 'text',
      category: '基本设置',
      description: '网站的显示名称',
      updatedAt: '2024-01-20'
    },
    {
      id: '2',
      key: 'site_description',
      name: '网站描述',
      value: '专业的汽车展示和销售平台',
      type: 'text',
      category: '基本设置',
      description: '网站的SEO描述',
      updatedAt: '2024-01-20'
    },
    {
      id: '3',
      key: 'max_upload_size',
      name: '最大上传大小',
      value: '10',
      type: 'number',
      category: '文件设置',
      description: '文件上传的最大大小(MB)',
      updatedAt: '2024-01-19'
    },
    {
      id: '4',
      key: 'enable_registration',
      name: '允许注册',
      value: 'true',
      type: 'boolean',
      category: '用户设置',
      description: '是否允许新用户注册',
      updatedAt: '2024-01-18'
    },
    {
      id: '5',
      key: 'email_settings',
      name: '邮件设置',
      value: '{"smtp_host":"smtp.example.com","smtp_port":587,"smtp_user":"admin@example.com"}',
      type: 'json',
      category: '邮件设置',
      description: 'SMTP邮件服务器配置',
      updatedAt: '2024-01-17'
    },
    {
      id: '6',
      key: 'cars_per_page',
      name: '每页车辆数',
      value: '12',
      type: 'number',
      category: '显示设置',
      description: '列表页面每页显示的车辆数量',
      updatedAt: '2024-01-16'
    },
    {
      id: '7',
      key: 'maintenance_mode',
      name: '维护模式',
      value: 'false',
      type: 'boolean',
      category: '系统设置',
      description: '是否开启网站维护模式',
      updatedAt: '2024-01-15'
    }
  ];

  useEffect(() => {
    if (!user || user.role !== 'admin') {
      router.push('/login');
      return;
    }

    setTimeout(() => {
      setConfigs(mockConfigs);
      setIsLoading(false);
    }, 1000);
  }, [user, router]);

  const handleUpdateConfig = (configId: string, newValue: string) => {
    setConfigs(configs.map(config => 
      config.id === configId 
        ? { ...config, value: newValue, updatedAt: new Date().toISOString().split('T')[0] }
        : config
    ));
  };

  const categories = Array.from(new Set(configs.map(config => config.category)));
  
  const filteredConfigs = selectedCategory === 'all' 
    ? configs 
    : configs.filter(config => config.category === selectedCategory);

  if (!user || user.role !== 'admin') {
    return null;
  }

  return (
    <>
      {/* Header */}
      <div className="mb-8">
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">系统配置</h1>
            <p className="text-gray-600">管理系统参数和设置</p>
          </div>
        </div>
      </div>

      {/* Category Filter */}
      <div className="mb-6">
        <div className="flex space-x-2">
          <button
            onClick={() => setSelectedCategory('all')}
            className={`px-4 py-2 rounded-lg text-sm font-medium ${
              selectedCategory === 'all'
                ? 'bg-blue-600 text-white'
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
          >
            全部
          </button>
          {categories.map(category => (
            <button
              key={category}
              onClick={() => setSelectedCategory(category)}
              className={`px-4 py-2 rounded-lg text-sm font-medium ${
                selectedCategory === category
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              {category}
            </button>
          ))}
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div className="bg-blue-50 rounded-lg shadow-sm p-6 border border-blue-100">
          <div className="text-2xl font-bold text-blue-600">{configs.length}</div>
          <div className="text-gray-600">总配置项</div>
        </div>
        <div className="bg-green-50 rounded-lg shadow-sm p-6 border border-green-100">
          <div className="text-2xl font-bold text-green-600">{categories.length}</div>
          <div className="text-gray-600">配置分类</div>
        </div>
        <div className="bg-purple-50 rounded-lg shadow-sm p-6 border border-purple-100">
          <div className="text-2xl font-bold text-purple-600">
            {configs.filter(c => c.type === 'boolean' && c.value === 'true').length}
          </div>
          <div className="text-gray-600">已启用功能</div>
        </div>
        <div className="bg-orange-50 rounded-lg shadow-sm p-6 border border-orange-100">
          <div className="text-2xl font-bold text-orange-600">
            {configs.filter(c => c.updatedAt === new Date().toISOString().split('T')[0]).length}
          </div>
          <div className="text-gray-600">今日更新</div>
        </div>
      </div>

      {/* Configs Table */}
      <div className="bg-white rounded-lg shadow-sm overflow-hidden border">
        <div className="px-6 py-4 border-b border-gray-200 bg-gray-50">
          <h2 className="text-xl font-semibold text-gray-900">
            配置列表 ({filteredConfigs.length})
          </h2>
        </div>
        
        {isLoading ? (
          <div className="p-8 text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-4 text-gray-600">加载中...</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    配置项
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    当前值
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    类型
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    分类
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    更新时间
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {filteredConfigs.map((config) => (
                  <tr key={config.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div>
                        <div className="text-sm font-medium text-gray-900">{config.name}</div>
                        <div className="text-sm text-gray-500">{config.key}</div>
                        <div className="text-xs text-gray-400">{config.description}</div>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-sm text-gray-900">
                        {config.type === 'boolean' ? (
                          <span className={`px-2 py-1 text-xs font-semibold rounded-full ${
                            config.value === 'true' 
                              ? 'bg-green-100 text-green-800' 
                              : 'bg-red-100 text-red-800'
                          }`}>
                            {config.value === 'true' ? '启用' : '禁用'}
                          </span>
                        ) : config.type === 'json' ? (
                          <code className="bg-gray-100 px-2 py-1 rounded text-xs">
                            {config.value.length > 50 ? config.value.substring(0, 50) + '...' : config.value}
                          </code>
                        ) : (
                          config.value
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={`px-2 py-1 text-xs font-semibold rounded-full ${
                        config.type === 'text' ? 'bg-blue-100 text-blue-800' :
                        config.type === 'number' ? 'bg-green-100 text-green-800' :
                        config.type === 'boolean' ? 'bg-purple-100 text-purple-800' :
                        'bg-orange-100 text-orange-800'
                      }`}>
                        {config.type}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                      {config.category}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                      {config.updatedAt}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                      <button
                        onClick={() => setEditingConfig(config)}
                        className="text-blue-600 hover:text-blue-900"
                      >
                        编辑
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Edit Config Modal */}
      {editingConfig && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md">
            <h3 className="text-lg font-semibold mb-4">编辑配置: {editingConfig.name}</h3>
            <form 
              onSubmit={(e) => {
                e.preventDefault();
                const formData = new FormData(e.target as HTMLFormElement);
                const newValue = formData.get('value') as string;
                handleUpdateConfig(editingConfig.id, newValue);
                setEditingConfig(null);
              }}
              className="space-y-4"
            >
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">配置键</label>
                <input
                  type="text"
                  value={editingConfig.key}
                  disabled
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 bg-gray-100"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">描述</label>
                <p className="text-sm text-gray-600">{editingConfig.description}</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">值</label>
                {editingConfig.type === 'boolean' ? (
                  <select
                    name="value"
                    defaultValue={editingConfig.value}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="true">启用</option>
                    <option value="false">禁用</option>
                  </select>
                ) : editingConfig.type === 'number' ? (
                  <input
                    type="number"
                    name="value"
                    defaultValue={editingConfig.value}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                ) : editingConfig.type === 'json' ? (
                  <textarea
                    name="value"
                    defaultValue={editingConfig.value}
                    rows={4}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm"
                  />
                ) : (
                  <input
                    type="text"
                    name="value"
                    defaultValue={editingConfig.value}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                )}
              </div>
              <div className="flex justify-end space-x-3 pt-4">
                <button
                  type="button"
                  onClick={() => setEditingConfig(null)}
                  className="px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
                >
                  取消
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                >
                  保存
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </>
  );
}